import 'dart:convert';
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_datetime_picker/flutter_cupertino_datetime_picker.dart';
import 'package:hitutor/UI/Account/Register.dart';
import 'package:hitutor/UI/Home/Home.dart';
import 'package:hitutor/UI/WebPage.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyButton.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:shared_preferences/shared_preferences.dart';

class Login extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _Login();
  }
}

class _Login extends State {
  TextEditingController accountController = TextEditingController();
  TextEditingController pswController = TextEditingController();

  loginClick() async {
    String account = accountController.text.trim();
    String psw = pswController.text.trim();
    if (account.isEmpty || psw.isEmpty) {
      return;
    }
    String auth = "$account:$psw";
    var bytes = utf8.encode(auth);
    var encode = base64Encode(bytes);
    Global.token = "Basic $encode";

    String registrationTokens = Global.firebasetoken;
    int pushProvider = Global.Firebase;
    if (Platform.isAndroid) {
      if (registrationTokens.isEmpty) {
        //android firebase 优先
        registrationTokens = Global.JPushRegToken;
        pushProvider = Global.JPush;
      }
    } else {
      if (Global.APNSToken.isNotEmpty) {
        //ios apn 优先
        registrationTokens = Global.APNSToken;
        pushProvider = Global.APN;
      }
    }

    HttpGo(context).post("/Login/GetTokenForAPP", {
      "deviceName": Global.deviceName,
      "os": Platform.operatingSystem,
      "osVersion": Global.systemVersion,
      "registrationTokens": registrationTokens,
      "ip": "",
      "location": "",
      "pushProvider": pushProvider
    }, (data) {
      Global.saveUserInfo(data["token"], data["studentId"], data["userId"], data["userName"], () {
        PageUtil().openReplace(context, Home());
      });
    }, (code, error) {
      showToast(error);
    }, showLoading: true);
  }

  clearToken() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setString("token", "");
  }

  switchDomain() {

  }

  @override
  initState() {
    clearToken();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
          alignment: Alignment.center,
          padding: EdgeInsets.fromLTRB(48, 0, 48, 0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              LocalImage("log-in.png", width: 200, onTap: switchDomain),
              Container(height: 24),
              Row(children: [
                LocalImage("user-7_dark.png", width: 24, padding: EdgeInsets.all(8)),
                Expanded(child: NormalInput(hintText: "請輸入信箱帳號", controller: accountController, inputType: NormalInput.Email))
              ]),
              Container(height: 1, color: MyColor.A0),
              Row(children: [
                LocalImage("key-lock-rect.png", width: 24, padding: EdgeInsets.all(8)),
                Expanded(child: NormalInput(hintText: "請輸入密碼", controller: pswController, inputType: NormalInput.Password))
              ]),
              Container(height: 1, color: MyColor.A0),
              TextBtn("忘記密碼", height: 44, alignment: Alignment.centerRight, style: TextStyle(color: MyColor.C66), onTap: () {
                PageUtil().open(context, WebPage("忘記密碼", HttpGo.ForgetUrl, showBrowser: true));
              }),
              Button("登入", width: double.infinity, margin: EdgeInsets.only(top: 24), onTap: loginClick),
              Button("註冊", width: double.infinity, margin: EdgeInsets.only(top: 12), onTap: () {
                PageUtil().open(context, Register());
              }),
              TextBtn("隱私權連結政策", height: 44, style: TextStyle(color: MyColor.C66, decoration: TextDecoration.underline), onTap: () {
                PageUtil().open(context, WebPage("隱私權連結政策", "https://tw.hitutoracdm.com/service.php#privacy_policy"));
              }),
            ],
          )),
    );
  }
}
